package com.lw.yygh.order.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.github.wxpay.sdk.WXPayConstants;
import com.github.wxpay.sdk.WXPayUtil;
import com.lw.yygh.enums.PaymentTypeEnum;
import com.lw.yygh.enums.RefundStatusEnum;
import com.lw.yygh.model.order.OrderInfo;
import com.lw.yygh.model.order.PaymentInfo;
import com.lw.yygh.model.order.RefundInfo;
import com.lw.yygh.order.service.OrderService;
import com.lw.yygh.order.service.PaymentService;
import com.lw.yygh.order.service.RefundService;
import com.lw.yygh.order.service.WeixinService;
import com.lw.yygh.order.utils.ConstantPropertiesUtils;
import com.lw.yygh.order.utils.HttpClient;
import lombok.val;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
public class WeixinServiceImpl implements WeixinService {
    @Autowired
    private OrderService orderService;
    @Autowired
    private PaymentService paymentService;
    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private RefundService refundService;
    //生成支付二维码
    @Override                               //订单编号
    public Map<String, Object> createNative(String orderId) {
        //从redis获取数据
        Map payMap = (Map) redisTemplate.opsForValue().get( orderId );
        if (payMap!=null){
            return payMap;
        }
        //根据id获取订单详情
        OrderInfo orderInfo = orderService.getOrder( orderId );
        //先向记录支付表中添加信息
        paymentService.savePaymentInfo(orderInfo, PaymentTypeEnum.WEIXIN.getStatus() );
        //设置参数，调用微信微信生成二维码接口
        Map paramMap = new HashMap();
        paramMap.put("appid", ConstantPropertiesUtils.APPID);
        paramMap.put("mch_id", ConstantPropertiesUtils.PARTNER);
        paramMap.put("nonce_str", WXPayUtil.generateNonceStr());
        String body = orderInfo.getReserveDate() + "就诊"+ orderInfo.getDepname();
        paramMap.put("body", body);
        paramMap.put("out_trade_no", orderInfo.getOutTradeNo());
        //paramMap.put("total_fee", order.getAmount().multiply(new BigDecimal("100")).longValue()+"");
        paramMap.put("total_fee", "1");//订单金额 0.01
        paramMap.put("spbill_create_ip", "127.0.0.1");
        paramMap.put("notify_url", "http://guli.shop/api/order/weixinPay/weixinNotify");//回调地址，还未使用
        paramMap.put("trade_type", "NATIVE");
        //调用微信生成二维码接口
        HttpClient client = new HttpClient( "https://api.mch.weixin.qq.com/pay/unifiedorder" );
        try {
            //把参数转换成xml格式，使用商户key进行加密
            client.setXmlParam( WXPayUtil.generateSignedXml( paramMap,ConstantPropertiesUtils.PARTNERKEY ) );
            client.setHttps( true );//默认不支持
            client.post();
            //返回相关数据
            String xmlParam = client.getContent();
            //转换成map集合
            Map<String, String> resultMap = WXPayUtil.xmlToMap( xmlParam );
            //4、封装返回结果集
            Map map = new HashMap<>();
            map.put("orderId", orderId);
            map.put("totalFee", orderInfo.getAmount());
            map.put("resultCode", resultMap.get("result_code"));
            map.put("codeUrl", resultMap.get("code_url"));//二维码地址
            System.out.println(resultMap.get("code_url"));
            if(null != resultMap.get("result_code")) {
                //微信支付二维码2小时过期，可采取2小时未支付取消订单
                redisTemplate.opsForValue().set(orderId, map, 20, TimeUnit.MINUTES);
            }

            return map;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    @Override
    public Map<String, String> queryPayStatus(String orderId, String name) {
        //获取订单
        OrderInfo orderInfo = orderService.getOrder( orderId );
        //封装提交参数
        Map paramMap = new HashMap<>();
        paramMap.put("appid", ConstantPropertiesUtils.APPID);
        paramMap.put("mch_id", ConstantPropertiesUtils.PARTNER);
        paramMap.put("out_trade_no", orderInfo.getOutTradeNo());
        paramMap.put("nonce_str", WXPayUtil.generateNonceStr());
        //设置请求参数
        HttpClient client = new HttpClient("https://api.mch.weixin.qq.com/pay/orderquery");
        try {
            client.setXmlParam( WXPayUtil.generateSignedXml( paramMap,ConstantPropertiesUtils.PARTNERKEY ) );
            client.setHttps( true );
            client.post();
            //得到返回数据
            String xml = client.getContent();
            Map<String, String> map = WXPayUtil.xmlToMap( xml );
            System.out.println(map);
            return map;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    //微信退款操作
    @Override
    public Boolean refund(String orderId) {
        try {
            //获取支付记录信息
            PaymentInfo paymentInfo = paymentService.getPaymentInfo( orderId, PaymentTypeEnum.WEIXIN.getStatus() );
            //添加信息到退款记录表
            RefundInfo refundInfo = refundService.saveRefundInfo( paymentInfo );
            //判断当前订单数据是否已经退款
            if (refundInfo.getRefundStatus().intValue()== RefundStatusEnum.REFUND.getStatus()){
                return true;
            }
            //调用微信接口实现退款
            Map<String,String> paramMap = new HashMap<>(8);
            paramMap.put("appid",ConstantPropertiesUtils.APPID);       //公众账号ID
            paramMap.put("mch_id",ConstantPropertiesUtils.PARTNER);   //商户编号
            paramMap.put("nonce_str",WXPayUtil.generateNonceStr());
            paramMap.put("transaction_id",paymentInfo.getTradeNo()); //微信订单号
            paramMap.put("out_trade_no",paymentInfo.getOutTradeNo()); //商户订单编号
            paramMap.put("out_refund_no","tk"+paymentInfo.getOutTradeNo()); //商户退款单号
//       paramMap.put("total_fee",paymentInfoQuery.getTotalAmount().multiply(new BigDecimal("100")).longValue()+"");
//       paramMap.put("refund_fee",paymentInfoQuery.getTotalAmount().multiply(new BigDecimal("100")).longValue()+"");
            paramMap.put("total_fee","1");
            paramMap.put("refund_fee","1");
            String paramXml = WXPayUtil.generateSignedXml(paramMap,ConstantPropertiesUtils.PARTNERKEY);
            //设置调用接口
            HttpClient httpClient = new HttpClient( "https://api.mch.weixin.qq.com/secapi/pay/refund" );
            httpClient.setXmlParam( paramXml );
            httpClient.setHttps( true );
            //设置证书
            httpClient.setCert( true );
            httpClient.setCertPassword(ConstantPropertiesUtils.PARTNER);
            httpClient.post();
            //接受返回数据
            String xml = httpClient.getContent();
            Map<String, String> resultMap = WXPayUtil.xmlToMap( xml );
            //通过返回数据判断是否退款成功
            if (null != resultMap && WXPayConstants.SUCCESS.equalsIgnoreCase(resultMap.get("result_code"))) {
                refundInfo.setCallbackTime( new Date() );
                refundInfo.setTradeNo( resultMap.get( "refund_id" ) );
                refundInfo.setRefundStatus( RefundStatusEnum.REFUND.getStatus() );
                refundInfo.setCallbackContent( JSONObject.toJSONString( resultMap ) );
                //更新退款记录状态
                refundService.updateById( refundInfo );
                return true;
            }
            return false;
            } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
}
